# 管理员功能
import os
import time
from interface import get_user_info, check_admin, check_login, login_user_dict, show_user_info, get_check_username, \
    get_product_name
from interface import name_list
from db import read_data, save_data, creat_path
from conf import settings


def add_user():
    admin = login_user_dict.get("username")
    data_dict, username = get_user_info()
    flag, msg = save_data(tag='info', path=f"{username}_info.json", data=data_dict)
    if not flag:
        return msg
    admin_logger = settings.get_logger(tag='admin', username=username)
    log = f"{admin} 添加用户 {username} 成功！"
    admin_logger.info(log)
    return log


def check_one_user():
    flag, check_name = get_check_username()
    if not flag:
        return check_name
    flag, msg = show_user_info(username=check_name)
    if not flag:
        return msg
    print(msg)
    admin_logger = settings.get_logger(tag='admin', username=login_user_dict.get("username"))
    log = f"{login_user_dict.get('username')} 查看用户 {check_name} 成功"
    admin_logger.info(log)
    return log


def check_all_user():
    list_name = name_list()
    for i in list_name:
        flag, msg = show_user_info(username=i)
        if not flag:
            return msg
        print(msg)
        time.sleep(0.5)
    admin_logger = settings.get_logger(tag='admin', username=login_user_dict.get("username"))
    log = f"{login_user_dict.get('username')} 查看所有用户成功"
    admin_logger.info(log)
    return log


def del_one_user():
    flag, check_name = get_check_username()
    if not flag:
        return check_name
    path_info = creat_path(tag='info', path=f"{check_name}_info.json")
    path_log = creat_path(tag='log', path=f"{check_name}_log.log")
    os.remove(path_log)
    os.remove(path_info)
    admin_logger = settings.get_logger(tag='admin', username=login_user_dict.get("username"))
    log = f"{login_user_dict.get('username')} 注销用户{check_name}成功"
    admin_logger.info(log)
    return log


def del_all_user():
    confirm = input("是否确认删除所有用户:y/n").strip()
    if confirm != 'y':
        return "已退出！"
    list_name = name_list()
    for name in list_name:
        if name == 'lea4ning':
            pass
        path_info = creat_path(tag='info', path=f"{name}_info.json")
        path_log = creat_path(tag='log', path=f"{name}_log.log")
        os.remove(path_log)
        os.remove(path_info)
    admin_logger = settings.get_logger(tag='admin', username=login_user_dict.get("username"))
    log = f"{login_user_dict.get('username')} 注销所有用户成功"
    admin_logger.info(log)
    return log


def modify_user():
    flag, check_name = get_check_username()
    if not flag:
        return check_name
    data_dict, username = get_user_info(tag='renew')
    if not data_dict:
        return username
    if username != check_name:
        print("用户名不一致，请不要轻易修改用户名！可能会导致登录问题！已重置！")
        print(f"{check_name} >>> {username}")
        data_dict[check_name] = data_dict.pop(username)
        data_dict[check_name]['username'] = check_name
    level_modify = input(f"请选择是否需要修改 {check_name} 的权限【1 :管理员/ 0:用户】:").strip()
    if level_modify not in ['1', '0']:
        return "输入有误！"
    if level_modify == '1':
        data_dict[check_name]['is_admin'] = True
    else:
        pass
    balance_modify = input(f"请选择是否修改 {check_name} 的余额，原有金额{data_dict[check_name]['balance']},不修改则为1000 : ").strip()
    if balance_modify != '':
        if not balance_modify.isdigit():
            return "请输入数字！"
        else:
            balance_modify = int(balance_modify)
            data_dict[check_name]['balance'] = balance_modify
    flag, msg = save_data(tag='info', path=f"{check_name}_info.json", data=data_dict)
    if not flag:
        return msg
    admin_logger = settings.get_logger(tag='admin', username=login_user_dict.get("username"))
    log = f"{login_user_dict.get('username')} 修改用户{check_name} 成功"
    admin_logger.info(log)
    return log


def get_product_info():
    product_name = input("请输入商品名称:").strip()
    product_price = input("请输入商品单价:").strip()
    try:
        product_price = float(product_price)
    except ValueError:
        return False, "请输入正确的格式！"
    product_inventory = input("请输入商品库存:").strip()
    if not product_inventory.isdigit():
        return False, "请输入正确的格式！"
    product_inventory = int(product_inventory)
    product_info_dict = {
        'product_name': product_name, 'product_price': product_price, 'product_inventory': product_inventory
    }
    return True, product_info_dict


def add_product():
    admin = login_user_dict.get("username")
    flag, product_dict = read_data(tag='product', path='product_data.json')
    if not flag:
        return product_dict
    flag, product_info_dict = get_product_info()
    if not flag:
        return product_info_dict
    product_dict[product_info_dict['product_name']].update(product_info_dict)
    flag, msg = save_data(tag='product', path='product_data.json', data=product_dict)
    if not flag:
        return msg
    else:
        admin_logger = settings.get_logger(tag='admin', username=admin)
        msg = f"{admin}添加商品 {product_info_dict['product_name']} 成功"
        admin_logger.info(msg)
        product_logger = settings.get_logger(tag='product', username='product')
        product_logger.info(msg)
        return msg


def modify_product():
    flag, product_dict = get_product_name()
    product_name = product_dict['name']
    print(f"修改商品{product_name}")
    if not flag:
        return product_dict
    flag, product_info_dict = get_product_info()
    if not flag:
        return product_info_dict
    if product_dict['name'] != product_info_dict['product_name']:
        print(f"不可以修改商品名，已自动将{product_info_dict['product_name']} 自动修正为{product_name}")
    flag, reading_data = read_data(tag='product', path='product_data.json')
    if not flag:
        return reading_data
    reading_data[product_name].update(product_info_dict)
    flag_save, msg_save = save_data(tag='product', path='product_data.json', data=reading_data)
    if not flag_save:
        return msg_save
    admin_logger = settings.get_logger(tag='admin', username=login_user_dict.get("username"))
    log = f"{login_user_dict.get('username')} 修改商品{product_name} 成功"
    admin_logger.info(log)
    return log


def del_one_product():
    flag, product_dict = get_product_name()
    product_name = product_dict['name']
    flag, reading_data = read_data(tag='product', path='product_data.json')
    if not flag:
        return reading_data
    del reading_data[product_name]
    flag_product, msg_product = save_data(tag='product', path='product_data.json', data=reading_data)
    if not flag_product:
        return msg_product
    admin_logger = settings.get_logger(tag='admin', username=login_user_dict.get("username"))
    log = f"{login_user_dict.get('username')} 删除商品{product_name} 成功"
    admin_logger.info(log)
    return log


def del_all_product():
    confirm = input("是否确认删除所有商品:y/n").strip()
    if confirm != 'y':
        return "已退出！"
    product_dict = {}
    flag, msg = save_data(tag='product', path='product_data.json', data=product_dict)
    if not flag:
        return msg
    admin_logger = settings.get_logger(tag='admin', username=login_user_dict.get("username"))
    log = f"{login_user_dict.get('username')} 删除所有商品 成功"
    admin_logger.info(log)
    return log


def quit_system():
    return 'break'


func_menu = '''
====================== Manager System =====================
【1】用户
1.添加用户信息       2.查看指定用户信息     3.查看所有用户信息         
4.注销指定用户信息    5.注销所有用户信息     6.修改指定用户信息 
-----------------------------------------------------------
【2】商品    
7.添加商品          8.修改商品            9.删除指定商品
10.删除所有商品
-----------------------------------------------------------
【3】系统
11.退出管理系统                            
========================= 欢迎使用 ==========================
'''

Manager_func_dict = {
    1: add_user,
    2: check_one_user,
    3: check_all_user,
    4: del_one_user,
    5: del_all_user,
    6: modify_user,
    7: add_product,
    8: modify_product,
    9: del_one_product,
    10: del_all_product,
    11: quit_system,
}


@check_login
@check_admin
def admin_main():
    while True:
        time.sleep(1)
        print(func_menu)
        choice_func = input("请输入功能ID:>>>").strip()
        choice_func = int(choice_func)
        func = Manager_func_dict[choice_func]
        msg = func()
        if msg == 'break':
            time.sleep(1)
            break
        print(msg)
    return '管理员系统已退出'
